package com.ruoyi.framework.config;

import com.ruoyi.common.filter.RequestLoggingFilter;
import com.ruoyi.common.filter.XssFilter;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import javax.servlet.DispatcherType;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Filter配置
 *
 * @author ruoyi
 */
@Data
@Configuration
@ConfigurationProperties(value = "system.xss")
public class FilterConfig {

    private String excludes;

    private String urlPatterns;

    private Boolean enabled;

    private Set<String> logIncludeHeaders;

    @SuppressWarnings({"rawtypes", "unchecked"})
    @Bean
    @ConditionalOnProperty(value = "system.xss.enabled", havingValue = "true")
    public FilterRegistrationBean<XssFilter> xssFilterRegistration() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        registration.addUrlPatterns(urlPatterns.split(","));
        registration.setName("xssFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 20);
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("excludes", excludes);
        registration.setInitParameters(initParameters);
        return registration;
    }

    @Bean
    public RequestLoggingFilter loggingFilter() {
        RequestLoggingFilter loggingFilter = new RequestLoggingFilter();
        // 记录 客户端 IP信息
        loggingFilter.setIncludeClientInfo(true);
        // 记录请求头
        loggingFilter.setIncludeHeaders(true);
        // 如果记录请求头的话，可以指定哪些记录，哪些不记录
        loggingFilter.setHeaderPredicate(s -> logIncludeHeaders.contains(s));
        // 记录 请求体  特别是POST请求的body参数
        loggingFilter.setIncludePayload(true);
        // 请求体的大小限制 默认50
        loggingFilter.setMaxPayloadLength(10000);
        // 记录请求路径中的query参数
        loggingFilter.setIncludeQueryString(true);

        loggingFilter.setAfterMessagePrefix("http：");
        loggingFilter.setAfterMessageSuffix(";");
        loggingFilter.setBeforeLog(false);
        return loggingFilter;
    }
}
